package h0825;
/**
  * @description 删除倒数第n个节点
  * @author 不知名帅哥
  * @date 2024/8/25 17:06
  * @version 1.0
*/
public class DeleteNode {
    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    public static void main(String[] args) {
        ListNode root=new ListNode(1);
        root.next=new ListNode(2);
        root.next.next=new ListNode(3,new ListNode(4,new ListNode(5)));
        ListNode res = removeNthFromEnd(root, 2);
        while (res!=null){
            System.out.println(res.val);
            res=res.next;
        }
    }
    public static ListNode removeNthFromEnd(ListNode head, int n){
        //倒数第n个节点
        ListNode dummy = new ListNode(0); //哨兵节点
        dummy.next=head;
        ListNode slow=dummy;
        ListNode fast=dummy;

        for (int i = 0; i < n; i++) {
            fast=fast.next; //让快指针先走n个单位
        }
        while (fast.next!=null){
            fast=fast.next;
            slow=slow.next;
        }
        //slow就是前一个节点
        slow.next=slow.next.next;
        return dummy.next; //返回头节点
    }
}
